package com.lagou.handler;

import com.lagou.RpcRequest;
import com.lagou.util.SpringBeanUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RpcRequest rpcRequest = (RpcRequest) msg;
        /** 获取服务 bean */
        Object obj = SpringBeanUtils.getBean(Class.forName(rpcRequest.getClassName()));
        /** 成功获取服务bean 通过反射调用 */
        if(obj != null){
            /** 根据对象获取反射方法 */
            Method method = obj.getClass().getMethod(rpcRequest.getMethodName(),rpcRequest.getParameterTypes());
            /** 写入ctx */
            String result = (String) method.invoke(obj,rpcRequest.getParameters());
            ctx.writeAndFlush(new RpcRequest(new String[]{result}));
        }


    }


}
